package com.party.mobile.biz.crowdfund;

import com.party.common.utils.StringUtils;
import com.party.common.utils.img.CompressInput;
import com.party.core.model.YesNoStatus;
import com.party.core.service.cos.CosBizService;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import com.party.mobile.biz.file.FileBizService;
import com.party.mobile.web.dto.crowdfund.output.ProjectPosterOutput;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 众筹海报
 *
 * @author yifeng
 * @date 2018/7/23 0023
 * @time 上午 9:29
 */
@Service
public class PaintProjectPosterBiz {
    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private FileBizService fileBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    final int width = 750;
    final int height = 1334;
    final int textSplit = 81;
    final int spaceWidth = 12;
    final String fontName = "幼圆";
    final Color colorRed = new Color(232, 71, 63);
    final Color colorDark = new Color(62, 58, 57);
    final Color colorBlack = new Color(0, 0, 0);

    public byte[] draw(ProjectPosterOutput posterOutput) throws IOException {
        String formatName = "png";
        // 背景图路径
        String imagePath = getXmlPath() + "image" + File.separator + "bg_2.png";
        // 块背景路径
        String blockPath = getXmlPath() + "image" + File.separator + "bg_1.png";
        // 印章图路径
        String stampPath = getXmlPath() + "image" + File.separator + "stamp.png";
        // logo图路径
        String logoPath = getXmlPath() + "image" + File.separator + "logo.png";
        // 二维码图路径
        String qrcodePath = getXmlPath() + "image" + File.separator + "qrcode.jpg";
        // 错误图路径
        String errorPath = getXmlPath() + "image" + File.separator + "error.png";

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        /**
         * 设置背景图
         */
        {
            Graphics graphics = image.getGraphics();
            BufferedImage bgImage = ImageIO.read(new File(imagePath));
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(bgImage, 0, 0, width, height, null);
            graphics.dispose();
        }
        /**
         * 海报图
         */
        {
            Graphics graphics = image.createGraphics();
            BufferedImage posterImage = ImageIO.read(new URL(posterOutput.getProjectPic() + "?imageMogr2/auto-orient/crop/750x410"));
            graphics.drawImage(posterImage, 0, 0 + 1, width, 410, null);
            graphics.dispose();

//            Graphics2D titleText = image.createGraphics();
//            Font youYuanFont = new Font(fontName, Font.PLAIN, 19);
//
//            int textHeight = titleText.getFontMetrics(youYuanFont).getHeight();
//
//            int length = posterOutput.getProjectTitle().trim().getBytes("UTF-8").length;
//            if (length % textSplit == 0) {
//                length = length % textSplit + 1;
//            } else {
//                length = length / textSplit + 1;
//            }

            /**
             * 块背景
             */
//            {
//                graphics = image.createGraphics();
//                posterImage = ImageIO.read(new File(blockPath));
//                graphics.drawImage(posterImage, 0, 97, width, 147 + (length - 1) * (textHeight + 10), null);
//                graphics.dispose();
//            }

            /**
             * 机构名称
             */
//            {
//                Graphics2D orgNameText = image.createGraphics();
//                Font meiHeiFont = new Font("腾祥魅黑简", Font.PLAIN, 39);
//                drawText(orgNameText, meiHeiFont, colorRed, posterOutput.getOrgName(), getWidthX(orgNameText, meiHeiFont, posterOutput.getOrgName(), width), 157);
//            }

            /**
             * 项目标题
             */
//            {
//                for (int i = 0; i < length; i++) {
//                    drawSpace(StringUtils.substringByte(posterOutput.getProjectTitle(), (i * textSplit) + i, textSplit),
//                            width, 200 + i * (textHeight + 10), 1.12, titleText, youYuanFont, colorRed, 0, true);
//                }
//            }
        }
        /**
         * 线
         */
        {
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.white);
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Stroke s = new BasicStroke(3F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            graphics.setStroke(s);
            graphics.drawRect(0, 411, width, 1);
        }
        /**
         * 线
         */
        {
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(colorRed);
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Stroke s = new BasicStroke(3F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            graphics.setStroke(s);
            graphics.drawRect(0, 415, width, 1);
        }
        /**
         * 头像
         */
        {
            int circleX = 277;
            int circleY = 305;
            int circleWidth = 195;
            int circleHeight = 195;
            {
                Graphics2D g2 = image.createGraphics();
                g2.setComposite(AlphaComposite.Src);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.WHITE);
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(circleX, circleY, circleWidth, circleHeight);
                //需要保留的区域
                g2.setClip(shape);

                // 设置背景图
                BufferedImage bufferedImage = null;
                try {
                    String logo = posterOutput.getLogo();
                    if (logo.indexOf("http:") == -1 && logo.indexOf("https:") == -1 && logo.indexOf("image.myqcloud.com") != -1) {
                        logo = "http:" + logo;
                    }
                    bufferedImage = ImageIO.read(new URL(logo));
                    ByteArrayOutputStream successOutput = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "PNG", successOutput);

                    BufferedImage errorImage = ImageIO.read(new File(errorPath));
                    ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
                    ImageIO.write(errorImage, "PNG", errorOutput);

                    if (errorOutput.toString().equals(successOutput.toString())) {
                        bufferedImage = ImageIO.read(new File(logoPath));
                    } else {
                        if (logo.indexOf("image.myqcloud.com") != -1) {
                            logo += "?imageMogr2/auto-orient/crop/195x195";
                        }
                        bufferedImage = ImageIO.read(new URL(logo));
                    }
                } catch (Exception e) {
                    bufferedImage = ImageIO.read(new File(logoPath));
                }
                g2.drawImage(bufferedImage, circleX, circleY, circleWidth, circleHeight, null);
                g2.dispose();
            }

            {
                Graphics2D graphics = image.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
                //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
                Stroke s = new BasicStroke(4.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
                graphics.setStroke(s);
                graphics.setColor(colorRed);
                graphics.drawOval(circleX, circleY, circleWidth, circleHeight);
                graphics.dispose();
            }
        }
        /**
         * 用户信息
         */
        Graphics2D nickNameText = image.createGraphics();
        Font nickYouYuanFont = new Font(fontName, Font.PLAIN, 27);
        Graphics2D companyText = image.createGraphics();
        Font companyYouYuanFont = new Font(fontName, Font.PLAIN, 18);
        int nickTextHeight = nickNameText.getFontMetrics(nickYouYuanFont).getHeight();
        int companyTextHeight = companyText.getFontMetrics(companyYouYuanFont).getHeight();
        int nickSplit = 50;
        int companySplit = 60;
        String nickName = posterOutput.getNickName();
        String company = posterOutput.getCompany();
        int nickLength = StringUtils.isEmpty(nickName) ? 0 : nickName.trim().getBytes("UTF-8").length;
        int companyLength = StringUtils.isEmpty(company) ? 0 : company.trim().getBytes("UTF-8").length;
        if (nickLength > 0) {
            if (nickLength % nickSplit == 0) {
                nickLength = nickLength % nickSplit + 1;
            } else {
                nickLength = nickLength / nickSplit + 1;
            }
        }
        if (companyLength > 0) {
            if (companyLength % companySplit == 0) {
                companyLength = companyLength % companySplit + 1;
            } else {
                companyLength = companyLength / companySplit + 1;
            }
        }
        // 昵称 + 公司 的额外高度
        int moreHeight = 0;
        // + ((companyLength - 1) * (companyTextHeight + 5))
        // ((nickLength - 1) * (nickTextHeight + 5))

        {
            /**
             * 昵称
             */
            {
                if (StringUtils.isNotEmpty(posterOutput.getNickName())) {
                    for (int i = 0; i < nickLength; i++) {
                        drawSpace(StringUtils.substringByte(nickName, (i * nickSplit) + i, nickSplit), width,
                                545 + i * (nickTextHeight + 5), 1.12, nickNameText, nickYouYuanFont, colorDark, 0);
                    }
                }
            }
            /**
             * 公司名称
             */
            {
                if (StringUtils.isNotEmpty(posterOutput.getCompany())) {
                    for (int i = 0; i < companyLength; i++) {
                        drawSpace(StringUtils.substringByte(company, (i * companySplit) + i, companySplit), width,
                                (580 + i * (companyTextHeight + 5)) + (nickLength - 1) * (nickTextHeight + 5),
                                1.12, companyText, companyYouYuanFont, colorDark, 0);
                    }
                }
            }
        }
        /**
         * 印章
         */
        {
            {
                Graphics2D text = image.createGraphics();
                Font youYuanFont = new Font(fontName, Font.PLAIN, 45);
                String content = "恭喜您！";
                drawText(text, youYuanFont, colorRed, content, getWidthX(text, youYuanFont, content, width), 700 + moreHeight);
            }
            /**
             * 印章
             */
            {
                Graphics graphics = image.createGraphics();
                BufferedImage posterImage = ImageIO.read(new File(stampPath));
                // 缩小图片消除锯齿的平滑处理
                graphics.drawImage(posterImage.getScaledInstance(150, 150, Image.SCALE_SMOOTH),
                        480, 590 + moreHeight, 150, 150, null);
                graphics.dispose();
            }
        }
        /**
         * 众筹信息
         */
        {
            Font youYuanFont = new Font(fontName, Font.PLAIN, 29);
            Font impactFont = new Font("Impact", Font.PLAIN, 29);

            String text1Content = "共用时";
            String text2ContentMonthNum = PaintProjectPosterBiz.transfrom(posterOutput.getUseTimeMonth());
            String text2ContentDayNum = PaintProjectPosterBiz.transfrom(posterOutput.getUserTimeDay());
            String text2ContentHourNum = PaintProjectPosterBiz.transfrom(posterOutput.getUserTimeHour());
            String text2ContentMinuteNum = PaintProjectPosterBiz.transfrom(posterOutput.getUserTimeMinute());

            String text2ContentMonth = StringUtils.isEmpty(text2ContentMonthNum) ? "" : "个月";
            String text2ContentDay = StringUtils.isEmpty(text2ContentDayNum) ? "" : "天";
            String text2ContentHour = StringUtils.isNotEmpty(text2ContentHourNum) ? "时" : "";
            String text2ContentMinute = StringUtils.isNotEmpty(text2ContentMinuteNum) ? "分钟" : "";

            String text3Content = "完成";
            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
            df.applyPattern("#.##");
            String text4ContentMoneyNum = df.format(posterOutput.getMoney());
            String text4ContentMoney = "元";
            String text4Content = text4ContentMoneyNum + text4ContentMoney;
            String text5Content = "的众筹";

            int textY = 780 + moreHeight;

            StringBuilder sb = new StringBuilder();
            sb.append(text1Content);

            if (YesNoStatus.YES.getCode().equals(posterOutput.getIsMultiple())) {
                sb.append(text2ContentMonthNum + text2ContentMonth + text2ContentDayNum + text2ContentDay);
            } else {
                sb.append(text2ContentDayNum + text2ContentDay + text2ContentHourNum + text2ContentHour + text2ContentMinuteNum + text2ContentMinute);
            }
            sb.append(text3Content);
            sb.append(text4Content);
            sb.append(text5Content);

            Graphics2D text1 = image.createGraphics();

            int w1 = 0;
            int w2 = 0;

            if (YesNoStatus.NO.getCode().equals(posterOutput.getIsMultiple())) {
                w1 = getSpaceWidth(text1, youYuanFont, text1Content + text2ContentDay + text2ContentHour + text2ContentMinute + text3Content + text4ContentMoney + text5Content, 1, false);
                w2 = getSpaceWidth(text1, impactFont, text2ContentDayNum + text2ContentHourNum + text2ContentMinuteNum + text4ContentMoneyNum, 1, false);
            } else {
                w1 = getSpaceWidth(text1, youYuanFont, text1Content + text2ContentMonth + text2ContentDay + text3Content + text4ContentMoney + text5Content, 1, false);
                w2 = getSpaceWidth(text1, impactFont, text2ContentMonthNum + text2ContentDayNum + text4ContentMoneyNum, 1, false);
            }

            int text1X = (width - (w1 + w2)) / 2;
            drawText(text1, youYuanFont, colorBlack, text1Content, text1X, textY);

            int endX = 0;
            String endContent = "";


            if (YesNoStatus.YES.getCode().equals(posterOutput.getIsMultiple())) {
                /******************************* 2 **************************************/
                Graphics2D text2MonthNum = image.createGraphics();
                int text1Width1 = text1.getFontMetrics(youYuanFont).stringWidth(text1Content);
                int text2MonthNumX = text1X + text1Width1;
                if (StringUtils.isNotEmpty(text2ContentMonthNum)) {
                    drawText(text2MonthNum, impactFont, colorRed, text2ContentMonthNum, text2MonthNumX, textY);
                }

                /******************************* 月 **************************************/
                Graphics2D text2Month = image.createGraphics();
                int text2MonthNumWidth = text1.getFontMetrics(impactFont).stringWidth(text2ContentMonthNum);
                int text2MonthX = text2MonthNumX + text2MonthNumWidth;
                if (StringUtils.isNotEmpty(text2ContentMonth)) {
                    drawText(text2Month, youYuanFont, colorRed, text2ContentMonth, text2MonthX, textY);
                }

                /******************************* 2 **************************************/
                Graphics2D text2DayNum = image.createGraphics();
                int text1Width = text1.getFontMetrics(youYuanFont).stringWidth(text2ContentMonth);
                int text2DayNumX = text2MonthX + text1Width;
                if (StringUtils.isNotEmpty(text2ContentDayNum)) {
                    drawText(text2DayNum, impactFont, colorRed, text2ContentDayNum, text2DayNumX, textY);
                }

                /******************************* 天 **************************************/
                Graphics2D text2Day = image.createGraphics();
                int text2DayNumWidth = text1.getFontMetrics(impactFont).stringWidth(text2ContentDayNum);
                int text2DayX = text2DayNumX + text2DayNumWidth;
                if (StringUtils.isNotEmpty(text2ContentDayNum)) {
                    drawText(text2Day, youYuanFont, colorRed, text2ContentDay, text2DayX, textY);
                }

                endX = text2DayX;
                endContent = text2ContentDay;
            } else {
                /******************************* 2 **************************************/
                Graphics2D text2DayNum = image.createGraphics();
                int text1Width = text1.getFontMetrics(youYuanFont).stringWidth(text1Content);
                int text2DayNumX = text1X + text1Width;
                if (StringUtils.isNotEmpty(text2ContentDayNum)) {
                    drawText(text2DayNum, impactFont, colorRed, text2ContentDayNum, text2DayNumX, textY);
                }

                /******************************* 天 **************************************/
                Graphics2D text2Day = image.createGraphics();
                int text2DayNumWidth = text1.getFontMetrics(impactFont).stringWidth(text2ContentDayNum);
                int text2DayX = text2DayNumX + text2DayNumWidth;
                if (StringUtils.isNotEmpty(text2ContentDayNum)) {
                    drawText(text2Day, youYuanFont, colorRed, text2ContentDay, text2DayX, textY);
                }

                /******************************* 23 **************************************/
                Graphics2D text2HourNum = image.createGraphics();
                int text2DayWidth = text1.getFontMetrics(youYuanFont).stringWidth(text2ContentDay);
                int text2HourNumX = text2DayX + text2DayWidth;
                if (StringUtils.isNotEmpty(text2ContentHourNum)) {
                    drawText(text2HourNum, impactFont, colorRed, text2ContentHourNum, text2HourNumX, textY);
                }

                /******************************* 时 **************************************/
                Graphics2D text2Hour = image.createGraphics();
                int text2HourNumWidth = text1.getFontMetrics(impactFont).stringWidth(text2ContentHourNum);
                int text2HourX = text2HourNumX + text2HourNumWidth;
                if (StringUtils.isNotEmpty(text2ContentHourNum)) {
                    drawText(text2Hour, youYuanFont, colorRed, text2ContentHour, text2HourX, textY);
                }

                /******************************* 23 **************************************/
                Graphics2D text2MinuteNum = image.createGraphics();
                int text2HourWidth = text1.getFontMetrics(youYuanFont).stringWidth(text2ContentHour);
                int text2MinuteNumX = text2HourX + text2HourWidth;
                drawText(text2MinuteNum, impactFont, colorRed, text2ContentMinuteNum, text2MinuteNumX, textY);

                /******************************* 分 **************************************/
                Graphics2D text2Minute = image.createGraphics();
                int text2MinuteNumWidth = text1.getFontMetrics(impactFont).stringWidth(text2ContentMinuteNum);
                int text2MinuteX = text2MinuteNumX + text2MinuteNumWidth;
                drawText(text2Minute, youYuanFont, colorRed, text2ContentMinute, text2MinuteX, textY);

                endX = text2MinuteX;
                endContent = text2ContentMinute;
            }

            Graphics2D text3 = image.createGraphics();
            int text2Width = text1.getFontMetrics(youYuanFont).stringWidth(endContent);
            int text3X = endX + text2Width;
            drawText(text3, youYuanFont, colorBlack, text3Content, text3X, textY);

            Graphics2D text4MoneyNum = image.createGraphics();
            int text3Width = text3.getFontMetrics(youYuanFont).stringWidth(text3Content);
            int text4X = text3X + text3Width;
            drawText(text4MoneyNum, impactFont, colorRed, text4ContentMoneyNum, text4X, textY);

            Graphics2D text4Money = image.createGraphics();
            int text3MoneyNumWidth = text3.getFontMetrics(impactFont).stringWidth(text4ContentMoneyNum);
            int text4MoneyX = text4X + text3MoneyNumWidth;
            drawText(text4Money, youYuanFont, colorRed, text4ContentMoney, text4MoneyX, textY);

            Graphics2D text5 = image.createGraphics();
            int text4Width = text4Money.getFontMetrics(youYuanFont).stringWidth(text4ContentMoney);
            int text5X = text4MoneyX + text4Width;
            drawText(text5, youYuanFont, colorBlack, text5Content, text5X, textY);
        }
        {
            Font youYuanFont = new Font(fontName, Font.PLAIN, 32);
            Font impactFont = new Font("Impact", Font.PLAIN, 32);

            String text1Content = "共获得";
            String text2ContentPeopleNum = posterOutput.getSupportNum().toString();
            String text2ContentPeople = "人";
            String text3Content = "支持";

            StringBuilder sb = new StringBuilder();
            sb.append(text1Content);
            sb.append(text2ContentPeopleNum + text2ContentPeople);
            sb.append(text3Content);

            int textY = 840 + moreHeight;

            Graphics2D text1 = image.createGraphics();

            int w1 = getSpaceWidth(text1, youYuanFont, text1Content + text2ContentPeople + text3Content, 1, false);
            int w2 = getSpaceWidth(text1, impactFont, text2ContentPeopleNum, 1, false);

            int text1X = (width - (w1 + w2)) / 2;
            drawText(text1, youYuanFont, colorBlack, text1Content, text1X, textY);

            Graphics2D text2PeopleNum = image.createGraphics();
            int text1Width = text1.getFontMetrics(youYuanFont).stringWidth(text1Content);
            int text2X = text1X + text1Width;
            drawText(text2PeopleNum, impactFont, colorRed, text2ContentPeopleNum, text2X, textY);

            Graphics2D text2People = image.createGraphics();
            int text1PeopleNumWidth = text2PeopleNum.getFontMetrics(youYuanFont).stringWidth(text2ContentPeopleNum);
            int text2PeopleX = text2X + text1PeopleNumWidth;
            drawText(text2People, youYuanFont, colorRed, text2ContentPeople, text2PeopleX, textY);

            Graphics2D text3 = image.createGraphics();
            int text2Width = text2People.getFontMetrics(youYuanFont).stringWidth(text2ContentPeople);
            int text3X = text2PeopleX + text2Width;
            drawText(text3, youYuanFont, colorBlack, text3Content, text3X, textY);
        }
        Graphics2D text8 = image.createGraphics();
        int fontSize = 0;
        if (YesNoStatus.YES.getCode().equals(posterOutput.getIsMultiple())) {
            fontSize = 35;
        } else {
            fontSize = 23;
        }
        Font youYuanFont111 = new Font(fontName, Font.PLAIN, fontSize);
        Font youYuanFont222 = new Font("Impact", Font.BOLD, 35);
        String text1Content = "获得";
        String text3Content = "参赛资格";

        int textHeight = text8.getFontMetrics(youYuanFont111).getHeight();

        int textY = 890 + 10 + moreHeight;
        int newTextSplit = 68;

        StringBuilder sb = new StringBuilder();
        sb.append(text1Content);
        if (YesNoStatus.YES.getCode().equals(posterOutput.getIsMultiple())) {
            if (posterOutput.getSuccessCount() > 1) {
                sb.append(posterOutput.getSuccessCount() + "场");
            }
        } else {
            sb.append(posterOutput.getProjectTitle().trim());
        }
        sb.append(text3Content);

        int length = sb.toString().getBytes("UTF-8").length;
        if (length % newTextSplit == 0) {
            length = length % newTextSplit + 1;
        } else {
            length = length / newTextSplit + 1;
        }

        drawProjectTitle(sb.toString(), length, newTextSplit, text8, youYuanFont111, youYuanFont222, textY, textHeight + 7, posterOutput.getIsMultiple());

        int rectHeight2 = 0;

        // 参赛资格的高度
        int otherHeight = length * textHeight + moreHeight;
        int placeY = textY + otherHeight + 20;
        {
            if (YesNoStatus.NO.getCode().equals(posterOutput.getIsMultiple())) {
                int baseWidth = 34;
                newTextSplit = 78;
                Font youYuanFont = new Font(fontName, Font.PLAIN, 20);
                Graphics2D graphics2D = image.createGraphics();
                String content = posterOutput.getStartDate() + " " + posterOutput.getPlace();
                int placeLength = content.getBytes("UTF-8").length;
                if (placeLength % newTextSplit == 0) {
                    placeLength = placeLength % newTextSplit + 1;
                } else {
                    placeLength = placeLength / newTextSplit + 1;
                }

                // 第一行文字
                String newStr = StringUtils.substringByte(content, (0 * newTextSplit) + 0, newTextSplit);

                int baseHeight = (placeLength - 1) * graphics2D.getFontMetrics(youYuanFont).getHeight();

                int circleWidth2 = baseWidth + baseHeight;

                // 长方形的高
                int rectHeight = baseWidth + baseHeight;

                rectHeight2 = baseWidth + (placeLength * graphics2D.getFontMetrics(youYuanFont).getHeight());

                int initX = getWidthX(graphics2D, youYuanFont, newStr, width); // 开始写字的位置

                // baseWidth / 2 等于左边的空白
                // circleWidth2 / 2 等于左边的半圆
//            int text2Width = initX - circleWidth2 / 2 - circleWidth2 / 2;
                int text2Width = initX - circleWidth2 / 2;

                int rectWidth = getTextWidth(newStr, graphics2D, youYuanFont);

                // 左边的半圆
                {
                    Graphics2D text = image.createGraphics();
                    text.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    text.setColor(colorRed);
                    text.fillArc(text2Width, placeY, circleWidth2, circleWidth2, 0, 360);
                }

                // 左边的空白
//            {
//                Graphics2D text = image.createGraphics();
//                text.setColor(colorRed);
//                text.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//                text.fillRect(text2Width + circleWidth2 / 2, placeY, circleWidth2 / 2, rectHeight);
//            }

                // 中间的空白
                {
                    Graphics2D text = image.createGraphics();
                    text.setColor(colorRed);
                    text.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//                text.fillRect(text2Width + circleWidth2 / 2 + circleWidth2 / 2, placeY, rectWidth, rectHeight);
                    text.fillRect(text2Width + circleWidth2 / 2, placeY, rectWidth, rectHeight);
                }

                // 右边的空白
//            {
//                Graphics2D text = image.createGraphics();
//                text.setColor(colorRed);
//                text.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//                text.fillRect(text2Width + circleWidth2 / 2 + circleWidth2 / 2 + rectWidth, placeY, circleWidth2 / 2, rectHeight);
//            }

                // 右边的半圆
                {
                    Graphics2D text = image.createGraphics();
                    text.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    text.setColor(colorRed);
//                text.fillArc(text2Width + circleWidth2 / 2 + circleWidth2 / 2 + rectWidth + circleWidth2 / 2 - circleWidth2 / 2, placeY, circleWidth2, circleWidth2,  0, 360);
                    text.fillArc(text2Width + circleWidth2 / 2 + rectWidth - circleWidth2 / 2, placeY, circleWidth2, circleWidth2, 0, 360);
                }

//            drawText(graphics2D, youYuanFont, Color.WHITE, content, text2Width + baseWidth + baseWidth / 2, baseY - 10);

                drawPlace(content, placeLength, newTextSplit, graphics2D, youYuanFont, placeY + 24);
            }
        }

        {
            int baseData = 145;

            int baseY = placeY + rectHeight2 + 20;

            /**
             * 二维码
             */
            {
                Graphics graphics = image.createGraphics();
                BufferedImage posterImage;
                try {
                    posterImage = ImageIO.read(new URL(posterOutput.getQrcodeUrl()));
                } catch (Exception e) {
                    posterImage = ImageIO.read(new File(qrcodePath));
                }
                // 缩小图片消除锯齿的平滑处理
                graphics.drawImage(posterImage.getScaledInstance(baseData, baseData, Image.SCALE_SMOOTH),
                        (width - baseData) / 2, baseY, baseData, baseData, null);
                graphics.dispose();
            }
            {
                Graphics graphics = image.createGraphics();
                graphics.setColor(colorDark);
                graphics.fillRect((width - baseData) / 2, baseY + baseData, baseData, 32);
            }
            {
                Font youYuanFont = new Font(fontName, Font.PLAIN, 18);
                Graphics2D graphics = image.createGraphics();
                drawSpace("扫码报名赛事", width, baseY + baseData + 22, 1.12, graphics, youYuanFont, Color.WHITE, ((width - baseData) / 2) + 15);
            }
        }


//        BufferedImage newImage = new BufferedImage(width, height + moreHeight, BufferedImage.TYPE_4BYTE_ABGR);
//        Graphics2D graphics2D = newImage.createGraphics();
//        graphics2D.drawImage(image, 0, 0, width, height + moreHeight, null);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //保存新图片
        ImageIO.write(image, formatName, bos);
        return bos.toByteArray();
    }

    public int getTextWidth(String content, Graphics2D graphics2D, Font font) {
        int width = 0;
        for (int j = 0; j < content.split("").length; j++) {
            String splitStr = content.split("")[j];
            width = getTempWidth(width, splitStr, graphics2D, font);
        }
        return width;
    }


    public static void drawText(Graphics2D graphics, Font font, Color color, String content, int x, int y) {
        graphics.setFont(font);
        graphics.setColor(color);
//        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB));
        graphics.drawString(content, x, y);
    }

    /**
     * 获取文字居中宽度
     *
     * @param graphics 画布
     * @param font     字体
     * @param content  内容
     * @param width    宽度
     * @return
     */
    public int getWidthX(Graphics graphics, Font font, String content, int width) {
        int textWidth = graphics.getFontMetrics(font).stringWidth(content);
        int widthX = (width - textWidth) / 2;
        return widthX;
    }

    /**
     * 获取待字间距的文字居中宽度
     *
     * @param graphics 画布
     * @param font     字体
     * @param str      内容
     * @param space    间距倍数
     * @param width    宽度
     * @return
     */
    public int getSpaceWidthX(Graphics graphics, Font font, String str, double space, int width) {
        int tempWidth = getSpaceWidth(graphics, font, str, space, true);
        return (width - tempWidth) / 2;
    }

    /**
     * 获取待字间距的文字居中宽度
     *
     * @param graphics 画布
     * @param font     字体
     * @param str      内容
     * @param space    间距倍数
     * @return
     */
    public int getSpaceWidth(Graphics graphics, Font font, String str, double space, boolean openTempLength) {
        String tempStr;
        int orgStringWight = graphics.getFontMetrics(font).stringWidth(str);
        int orgStringLength = openTempLength ? (int) getTempLength(str) : str.length();

        int tempX = 0;
        while (str.length() > 0) {
            tempStr = str.substring(0, 1);
            str = str.substring(1, str.length());

            if (StringUtils.isContainEnglish(tempStr)) {
                tempX += (int) (spaceWidth * (space));
            } else {
                tempX += (int) ((double) orgStringWight / (double) orgStringLength * space);
            }
        }
        return tempX;
    }

    private double getTempLength(String str) {
        double tempLength = 0d;
        for (String string : str.split("")) {
            if (StringUtils.isContainEnglish(string) || StringUtils.isContainSymbol(string)) {
                tempLength += 0.5;
            } else if (StringUtils.isContainChinese(string) || string.equals("【") || str.equals("】")) {
                tempLength += 1;
            } else {
                tempLength += 0.5;
            }
        }
        return tempLength;
    }

    /**
     * 文字自定义行距
     *
     * @param content   文字内容
     * @param width     宽度
     * @param positionY y坐标
     * @param space     行距
     * @param graphics  画布
     * @param font      字体
     */
    public void drawSpace(String content, int width, int positionY, double space, Graphics2D graphics, Font font, Color color, int positionX) {
        graphics.setFont(font);
        graphics.setColor(color);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB));

        int tempWidth = getTextWidth(content, graphics, font);
        int tempX = (width - tempWidth) / 2;
        String tempStr;

        String[] array = content.split("");
        for (int i = 0; i < array.length; i++) {
            tempStr = array[i];
            graphics.drawString(tempStr, tempX, positionY);
            tempX = getTempWidth(tempX, tempStr, graphics, font);
        }
    }

    /**
     * @param str          文字内容
     * @param length       长度
     * @param newTextSplit 分割长度
     * @param graphics
     * @param font         字体
     * @param positionY    y轴位置
     * @return void
     * @Author yifeng
     * @Description 画城市
     * @Date 15:17 2019/2/13
     **/
    public void drawPlace(String str, int length, int newTextSplit,
                          Graphics2D graphics, Font font, int positionY) {

        int textHeight = graphics.getFontMetrics(font).getHeight();
        graphics.setColor(Color.WHITE);
        graphics.setFont(font);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB));
        for (int i = 0; i < length; i++) {
            String newStr = StringUtils.substringByte(str, (i * newTextSplit) + i, newTextSplit);
            int initX = getWidthX(graphics, font, newStr, width);
            int tempX = initX;
            for (int j = 0; j < newStr.split("").length; j++) {
                String splitStr = newStr.split("")[j];
                graphics.drawString(splitStr, tempX, positionY + (int) (i * textHeight));
                tempX = getTempWidth(tempX, splitStr, graphics, font);
            }
        }
    }

    /**
     * @param str 内容
     * @param length 长度
     * @param newTextSplit 分割长度
     * @param graphics
     * @param font 字体
     * @param positionY y轴
     * @param textHeight
     * @param isMultiple
     * @return void
     * @Author yifeng
     * @Description 画 获得参赛资格
     * @Date 15:43 2019/2/13
     **/
    public void drawProjectTitle(String str, int length, int newTextSplit,
                                 Graphics2D graphics, Font font, Font font2, int positionY, int textHeight, Integer isMultiple) {
        String content = "获得参赛资格";
        graphics.setFont(font);
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB));
        int tempLength = 0;
        for (int i = 0; i < length; i++) {
            String newStr = StringUtils.substringByte(str, (i * newTextSplit) + i, newTextSplit);
            int newLength = newStr.length();

            int tempWidth = getTextWidth(newStr, graphics, font);
            int initX = (width - tempWidth) / 2;

            tempWidth = initX;
            for (int j = 0; j < newStr.split("").length; j++) {
                String splitStr = newStr.split("")[j];
                boolean findFlag = false;
                for (int k = 0; k < content.split("").length; k++) {
                    if (splitStr.equals(content.split("")[k])) {
                        if ((splitStr.equals("获") && j == 0)
                                || (splitStr.equals("得") && j == 1)
                                || (splitStr.equals("参") && j + (tempLength) == str.length() - 4)
                                || (splitStr.equals("赛") && j + (tempLength) == str.length() - 3)
                                || (splitStr.equals("资") && j + (tempLength) == str.length() - 2)
                                || (splitStr.equals("格") && j + (tempLength) == str.length() - 1)) {
                            findFlag = true;
                            break;
                        }
                    }
                }
                if (findFlag) {
                    graphics.setColor(colorBlack);
                } else {
                    graphics.setColor(colorRed);
                }
                if (YesNoStatus.YES.getCode().equals(isMultiple) && NumberUtils.isNumber(splitStr)) {
                    graphics.setFont(font2);
                } else {
                    graphics.setFont(font);
                }
                graphics.drawString(splitStr, tempWidth, positionY + i * textHeight);

                tempWidth = getTempWidth(tempWidth, splitStr, graphics, font);
            }
            tempLength += newLength;
        }
    }

    private int getTempWidth(int tempWidth, String splitStr, Graphics2D graphics, Font font) {
        int orgStringWight = graphics.getFontMetrics(font).stringWidth(splitStr);
        if (StringUtils.isContainEnglish(splitStr)) {
            tempWidth = tempWidth + orgStringWight;
        } else if (StringUtils.isContainSymbol(splitStr) || " ".equals(splitStr)) {
            tempWidth = tempWidth + 6;
        } else {
            tempWidth = tempWidth + orgStringWight;
        }
        return tempWidth;
    }

    /**
     * 上传众筹海报到万象优图
     *
     * @param posterOutput 海报数据
     * @return 文件字节数组
     */
    public byte[] projectPosterUploadCI(ProjectPosterOutput posterOutput) {
        try {
            long start = System.currentTimeMillis();
            String fileName = posterOutput.getProjectId() + ".png";
            String filePath = String.format("/%s/%s/", posterOutput.getAuthorId(), "zcPoster");
            byte[] bytes = draw(posterOutput);
            long end = System.currentTimeMillis();
            logger.info("projectPosterUploadCI  生成成功海报用时：{}", (end - start));

//            OutputStream outputStream = new FileOutputStream(new File(getXmlPath() + "raisePostersImg" + File.separator + posterOutput.getProjectId() + ".png"));
//            outputStream.write(bytes);
//            outputStream.close();


            long start1 = System.currentTimeMillis();
            try {
                ByteArrayInputStream input = new ByteArrayInputStream(bytes);
                CompressInput compressInput = new CompressInput();
                compressInput.setMaxWidth(750);
                compressInput.setImgInput(input);
                compressInput.setFormatName("png");
                compressInput.setFileName(posterOutput.getProjectId());
                UploadResult uploadResult = cosBizService.uploadFile(input, filePath + fileName, InsertOnly.OVER_WRITE);
                String previewPicUrl = cosBizService.getPreviewPicUrl(uploadResult.getAccessUrl());
                logger.info(previewPicUrl);
            } catch (Exception e) {
                logger.error("海报上传腾讯云异常", e);
            }
            long end1 = System.currentTimeMillis();
            logger.info("projectPosterUploadCI  上传到腾讯云用时：{}", (end1 - start1));
            return bytes;
        } catch (Exception e) {
            logger.error("绘制海报异常", e);
            return null;
        }
    }

    public String getXmlPath() {
        String classPath = PaintProjectPosterBiz.class.getClassLoader().getResource("/").getPath();
        String rootPath = "";
        //windows下
        if ("\\".equals(File.separator)) {
            rootPath = classPath.substring(1, classPath.length() - 1);
            rootPath = rootPath.replace("/", "\\");
        }
        //linux下
        if ("/".equals(File.separator)) {
            rootPath = classPath.substring(0, classPath.length() - 1);
            rootPath = rootPath.replace("\\", "/");
        }
        rootPath = rootPath.replace("classes", "");
        return rootPath;
    }

    public byte[] getsupportersPosters(ProjectPosterOutput posterOutput,String supportersLoge,String amount) throws Exception {
        String formatName = "png";
        // 背景图路径(1-5随机生成)
        String imagePath = getXmlPath() + "image" + File.separator + "bg_zcz"+(int)(Math.random()*6+1)+".png";

        // 众筹者logo图路径
        String logoPath_zc =  posterOutput.getLogo();
        // 支持者logo图路径
        String logoPath_zcz =supportersLoge;
        // 默认logo图路径
        String logoPath = getXmlPath() + "image" + File.separator + "logo.png";
        // 二维码图路径
        String qrcodePath = posterOutput.getQrcodeUrl();
        // 错误图路径
        String errorPath = getXmlPath() + "image" + File.separator + "error.png";

        // 二维码图路径
        String defaultQrcodePath = getXmlPath() + "image" + File.separator + "qrcode.jpg";

        logger.info("众筹者logo图路径:"+logoPath_zc);
        logger.info("支持者logo图路径:"+supportersLoge);

        final int width = 750;
        final int height = 1334;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        /**
         * 设置背景图
         */
        {
            Graphics graphics = image.getGraphics();
            BufferedImage bgImage = ImageIO.read(new File(imagePath));
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(bgImage, 0, 0, width, height, null);
            graphics.dispose();
        }

        /**
         * 众筹者头像
         */
        {
            int circleX = 264;
            int circleY = 510;
            int circleWidth = 177;
            int circleHeight = 177;
            {
                Graphics2D g2 = image.createGraphics();
                g2.setComposite(AlphaComposite.Src);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.WHITE);
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(circleX, circleY, circleWidth, circleHeight);
                //需要保留的区域
                g2.setClip(shape);


                // 设置背景图
                BufferedImage bufferedImage = null;
                String logo = logoPath_zc;
                try {
                    if (logo.indexOf("http:") == -1 && logo.indexOf("https:") == -1 && logo.indexOf("image.myqcloud.com") != -1) {
                        logo = "http:" + logo;
                    }
                    bufferedImage = ImageIO.read(new URL(logo));
                    ByteArrayOutputStream successOutput = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "PNG", successOutput);

                    BufferedImage errorImage = ImageIO.read(new File(errorPath));
                    ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
                    ImageIO.write(errorImage, "PNG", errorOutput);

                    if (errorOutput.toString().equals(successOutput.toString())) {
                        bufferedImage = ImageIO.read(new File(logoPath));
                    } else {
                        if (logo.indexOf("image.myqcloud.com") != -1) {
                            logo += "?imageMogr2/auto-orient/crop/195x195";
                        }
                        bufferedImage = ImageIO.read(new URL(logo));
                    }
                } catch (Exception e){
                    logger.error("获取头像异常：logo：{}", logo, e);
                    bufferedImage = ImageIO.read(new File(logoPath));
                }
                g2.drawImage(bufferedImage, circleX, circleY, circleWidth, circleHeight, null);
                g2.dispose();
            }
            // 加盖一个黑色的圈，遮住锯齿
            {
                Graphics2D graphics = image.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
                //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
                Stroke s = new BasicStroke(8F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
                graphics.setStroke(s);
                graphics.setColor(colorBlack);
                graphics.drawOval(circleX, circleY, circleWidth, circleHeight);
                graphics.dispose();
            }
        }

        /**
         * 支持者头像
         */
        {
            int circleX = 85;
            int circleY = 150;
            int circleWidth = 175;
            int circleHeight = 175;
            {
                Graphics2D g2 = image.createGraphics();
                g2.setComposite(AlphaComposite.Src);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.WHITE);
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(circleX, circleY, circleWidth, circleHeight);
                //需要保留的区域
                g2.setClip(shape);


                // 设置背景图
                BufferedImage bufferedImage = null;
                try {
                    String logo = logoPath_zcz;
                    if (logo.indexOf("http:") == -1 && logo.indexOf("https:") == -1 && logo.indexOf("image.myqcloud.com") != -1) {
                        logo = "http:" + logo;
                    }
                    bufferedImage = ImageIO.read(new URL(logo));
                    ByteArrayOutputStream successOutput = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "PNG", successOutput);

                    BufferedImage errorImage = ImageIO.read(new File(errorPath));
                    ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
                    ImageIO.write(errorImage, "PNG", errorOutput);

                    if (errorOutput.toString().equals(successOutput.toString())) {
                        bufferedImage = ImageIO.read(new File(logoPath));
                    } else {
                        if (logo.indexOf("image.myqcloud.com") != -1) {
                            logo += "?imageMogr2/auto-orient/crop/195x195";
                        }
                        bufferedImage = ImageIO.read(new URL(logo));
                    }
                } catch (Exception e) {
                    bufferedImage = ImageIO.read(new File(logoPath));
                }
                g2.drawImage(bufferedImage, circleX, circleY, circleWidth, circleHeight, null);
                g2.dispose();
            }

            // 加盖一个黑色的圈，遮住锯齿
            {
                Graphics2D graphics = image.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
                //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
                Stroke s = new BasicStroke(8F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
                graphics.setStroke(s);
                graphics.setColor(colorBlack);
                graphics.drawOval(circleX, circleY, circleWidth, circleHeight);
                graphics.dispose();
            }
        }
        Font font_general = new Font("华文细黑", Font.PLAIN, 30);
        Font font_32BOLD = new Font("华文细黑", Font.BOLD, 32);
        Font font_amount = new Font("华文细黑", Font.PLAIN, 60);
        Font font_date = new Font("华文细黑", Font.PLAIN, 25);
        Font font_smbmss = new Font("华文细黑", Font.PLAIN, 22);

        String wog = "我给";
        String nickName = addBlank(getStrValue(posterOutput.getNickName(),6),"");
        String zcl = "支持了";
         amount = getStrValue(amount,8);
        String ztwcl = "助Ta完成";
        String projectName = posterOutput.getProjectTitle();
        String dmx = "的梦想";
        String StartTime = posterOutput.getStartDate();
        Map<String,String> addressMap = posterOutput.getPlaceMap();
        String activitiesaddress =addressMap.get("city")+addressMap.get("area")+addressMap.get("place");
        if(activitiesaddress.length()>10){
            activitiesaddress=addressMap.get("area")+addressMap.get("place");
            if(activitiesaddress.length()>10){
                activitiesaddress=addressMap.get("place");
                if(activitiesaddress.length()>10){
                    activitiesaddress=addressMap.get("city")+addressMap.get("area");
                    if(activitiesaddress.length()>10){
                        activitiesaddress=addressMap.get("area");
                        if(activitiesaddress.length()>10){
                            activitiesaddress=addressMap.get("city");
                        }
                    }
                }
            }
        }
        String smbmss = "扫码报名赛事";
        int text1X = 54;




        /**
         * 众筹信息---第1行
         */
        {

            int textY = 971;
            //我给
            Graphics2D text_wog = image.createGraphics();
            drawText(text_wog, font_general, colorBlack, wog, text1X, textY);

            //昵称
            Graphics2D text_nickName = image.createGraphics();
            int text_nickNameWidth = text_wog.getFontMetrics(font_general).stringWidth(wog);
            int text2X = text1X + text_nickNameWidth;

            drawText(text_nickName,font_32BOLD, colorBlack,nickName, text2X,textY);

            //支持了
            Graphics2D text_zcl = image.createGraphics();
            //固定位置
            int text3X = 366;
            drawText(text_zcl,font_general, colorBlack,zcl, text3X,textY);

            //金额
            Graphics2D text_amount = image.createGraphics();
            int text_amountWidth = text_zcl.getFontMetrics(font_general).stringWidth(zcl);
            int text4X = text_amountWidth + text3X;

            drawText(text_amount,font_amount, colorBlack,amount, text4X,textY);
        }
        /**
         * 众筹信息---第2行
         */
        {
            int textY = 1025;

            //帮他完成
            Graphics2D text_ztwcl = image.createGraphics();

            drawText(text_ztwcl, font_general, colorBlack, ztwcl, text1X, textY);

            //项目名称
            String projectName_2 = "";
            int textY_2 = textY;
            if(projectName.length()>15){
                String p1= projectName.substring(15,projectName.length());
                String p2 = projectName.substring(0,15);
                if(p1.length()>15){
                    p1 = getStrValue(p1,15);
                }
                projectName_2 = addBlank(p1,"after");
                projectName =addBlank(getStrValue(p2,15),"before");
                textY_2 = 1076;
            }else{
                projectName = addBlank(projectName,"");
            }

            //项目名称_长度小于15的部分
            Graphics2D text_projectName = image.createGraphics();

            int text_projectNameWidth = text_ztwcl.getFontMetrics(font_general).stringWidth(ztwcl);
            int text2X = text1X + text_projectNameWidth;

            drawText(text_projectName,font_32BOLD, colorBlack,projectName, text2X,textY);

            //项目名称_长度大于15的部分
            Graphics2D text_projectName_2 = image.createGraphics();

            drawText(text_projectName_2, font_32BOLD, colorBlack, projectName_2, text1X, textY_2);

            //的梦想
            Graphics2D text_dmx = image.createGraphics();

            String str = projectName;
            if(!"".equals(projectName_2)){
                str = projectName_2;
                text2X = text1X;
            }
            int text_dmxWidth = text_ztwcl.getFontMetrics(font_32BOLD).stringWidth(str);
            int text4X = text2X + text_dmxWidth;

            if(projectName_2.equals("")){
                Map<String,String> mmp = new HashMap<>();

                if(text_dmxWidth<=395){
                    mmp.put("a","的梦想");
                }else if(text_dmxWidth>395&&text_dmxWidth<=428){
                    mmp.put("a","的梦");
                    mmp.put("b","想");
                }else if(text_dmxWidth>428&&text_dmxWidth<=462){
                    mmp.put("a","的");
                    mmp.put("b","梦想");
                }else if(text_dmxWidth>462){
                    mmp.put("a","");
                    mmp.put("b","的梦想");
                }
                if(mmp.size()==2){
                    drawText(text_dmx,font_general, colorBlack,mmp.get("a"), text4X,textY_2);
                    textY_2 = 1076;
                    text4X = text1X;
                    drawText(text_dmx,font_general, colorBlack,mmp.get("b"), text4X,textY_2);
                }else{
                    drawText(text_dmx,font_general, colorBlack,mmp.get("a"), text4X,textY_2);
                }
            }else{
                textY_2 = 1076;
                drawText(text_dmx,font_general, colorBlack,dmx, text4X,textY_2);


            }
        }

        /**
         * 众筹信息---出发时间
         */
        {
            int textY = 1135;

            Graphics2D text_date = image.createGraphics();
            drawText(text_date, font_date, colorBlack, StartTime, text1X, textY);
        }
        /**
         * 众筹信息---地点
         */
        {
            int textY = 1135;
            Graphics2D text_date = image.createGraphics();
            int w2 = new PaintProjectPosterBiz().getSpaceWidth(text_date, font_date, activitiesaddress+StartTime, 1, false);
            text1X = (width - w2) / 2+33;
            drawText(text_date, font_date, colorBlack, activitiesaddress, text1X, textY);
        }
        /**
         * 众筹信息---扫码报名赛事
         */
        {
            int textY = 1135;
            Graphics2D text_date = image.createGraphics();
            int w2 = new PaintProjectPosterBiz().getSpaceWidth(text_date, font_smbmss, smbmss, 1, false);
            text1X =565;
            drawText(text_date, font_smbmss, colorBlack, smbmss, text1X, textY);
        }
        /**
         * 众筹信息---二维码
         */

        {
            int baseData = 135;
            Graphics graphics = image.createGraphics();
            BufferedImage posterImage;
            try {
                posterImage = ImageIO.read(new URL(posterOutput.getQrcodeUrl()));
            } catch (Exception e) {
                posterImage = ImageIO.read(new File(defaultQrcodePath));
            }
            // 缩小图片消除锯齿的平滑处理
            graphics.drawImage(posterImage.getScaledInstance(baseData, baseData, Image.SCALE_SMOOTH),
                    565, 1152, null);
            graphics.dispose();
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //保存新图片
        ImageIO.write(image, formatName, bos);
        return bos.toByteArray();
    }
    public   String getStrValue(String val,int length){
            System.out.println(val.length());
        if(val.length()>length){
            val= val.substring(0,length)+"...";
        }else{
            StringBuffer sbf = new StringBuffer();
            for(int i = 0;i<length-val.length();i++){
                sbf.append(" ");
            }
            val= sbf.toString()+val+sbf.toString();
        }
        return val;
    }
    public  String addBlank(String val,String atype){

        if("before".equalsIgnoreCase(atype)){
            val=" "+val;
        }else if("after".equalsIgnoreCase(atype)){
            val=val+" ";
        }
        return val.contains(" ")?val:" "+val+" ";
    }

    /**
     * @Description: 2019新年宣传海报
     * @Param:
     * @return:
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    public byte[] newYearPoster(ProjectPosterOutput posterOutput) throws IOException {

        String formatName = "png";
        // 背景图路径
        String imagePath = getXmlPath() + "image" + File.separator + "19newYear_bz.png";

        // logo图路径
        String logoPath = getXmlPath() + "image" + File.separator + "logo.png";
        // 二维码图路径
        String qrcodePath = getXmlPath() + "image" + File.separator + "qrcode.jpg";
        // 错误图路径
        String errorPath = getXmlPath() + "image" + File.separator + "error.png";


        final int width = 750;
        final int height = 1334;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        /**
         * 设置背景图
         */
        {
            Graphics graphics = image.getGraphics();
            BufferedImage bgImage = null;
            if(StringUtils.isNotEmpty(posterOutput.getNetworkImagePath())){
                try {
                     bgImage = ImageIO.read(new URL(posterOutput.getNetworkImagePath()));
                }catch (Exception e){
                     bgImage = ImageIO.read(new File(imagePath));
                }
            }else{
                bgImage = ImageIO.read(new File(imagePath));
            }
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(bgImage, 0, 0, width, height, null);
            graphics.dispose();
        }

        /**
         * 头像
         */
        {
            int circleX = 277;
            int circleY = 480;
            int circleWidth = 200;
            int circleHeight = 200;
            {
                Graphics2D g2 = image.createGraphics();
                g2.setComposite(AlphaComposite.Src);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.WHITE);
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(circleX, circleY, circleWidth, circleHeight);
                //需要保留的区域
                g2.setClip(shape);

                // 设置背景图
                BufferedImage bufferedImage = null;
                try {
                    String logo = posterOutput.getLogo();
                    if (logo.indexOf("http:") == -1 && logo.indexOf("https:") == -1 && logo.indexOf("image.myqcloud.com") != -1) {
                        logo = "http:" + logo;
                    }
                    bufferedImage = ImageIO.read(new URL(logo));
                    ByteArrayOutputStream successOutput = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "PNG", successOutput);

                    BufferedImage errorImage = ImageIO.read(new File(errorPath));
                    ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
                    ImageIO.write(errorImage, "PNG", errorOutput);

                    if (errorOutput.toString().equals(successOutput.toString())) {
                        bufferedImage = ImageIO.read(new File(logoPath));
                    } else {
                        if (logo.indexOf("image.myqcloud.com") != -1) {
                            logo += "?imageMogr2/auto-orient/crop/195x195";
                        }
                        bufferedImage = ImageIO.read(new URL(logo));
                    }
                } catch (Exception e) {
                    bufferedImage = ImageIO.read(new File(logoPath));
                }
                g2.drawImage(bufferedImage, circleX, circleY, circleWidth, circleHeight, null);
                g2.dispose();
            }

            {
                Graphics2D graphics = image.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
                //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
                Stroke s = new BasicStroke(3.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
                graphics.setStroke(s);
                graphics.setColor(colorBlack);
                graphics.drawOval(circleX, circleY, circleWidth, circleHeight);
                graphics.dispose();
            }
        }

        {
            //二维码
            {
                int circleX = 310;
                int circleY = 1100;
                int baseData = 125;

                Graphics graphics = image.createGraphics();
                BufferedImage posterImage;

                try {
                    posterImage = ImageIO.read(new URL(posterOutput.getPersonalQrCodeUrl()));
                } catch (Exception e) {
                    posterImage = ImageIO.read(new File(posterOutput.getPersonalQrCodeUrl()));
                }
                // 缩小图片消除锯齿的平滑处理
                graphics.drawImage(posterImage.getScaledInstance(baseData, baseData, Image.SCALE_SMOOTH),
                        circleX, circleY, null);
                graphics.dispose();
            }
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //保存新图片
        ImageIO.write(image, formatName, bos);
        return bos.toByteArray();
    }

    /**
     * @Description: 上传海报到腾讯云
     * @Param:
     * @return:
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    public String PosterUploadCI(String fileName, String filePath, byte[] bytes) throws Exception {

        String previewPicUrl = "";

        ByteArrayInputStream input = new ByteArrayInputStream(bytes);
        CompressInput compressInput = new CompressInput();
        compressInput.setMaxWidth(750);
        compressInput.setImgInput(input);
        compressInput.setFormatName("png");
        compressInput.setFileName(fileName);
        UploadResult uploadResult = cosBizService.uploadFile(input, filePath + fileName + ".png", InsertOnly.OVER_WRITE);
        previewPicUrl = cosBizService.getPreviewPicUrl(uploadResult.getAccessUrl());
        logger.info(previewPicUrl);

        return previewPicUrl;
    }


    /**
     * @Description: 福字宣传海报
     * @Param:
     * @return:
     * @Author: Hua Qunhao
     * @Date: 2019-01-23-0023
     */
    public byte[] blessingFontPoster(ProjectPosterOutput posterOutput) throws IOException {

        String formatName = "png";
        // 背景图路径
        String imagePath = getXmlPath() + "image" + File.separator + "blessingFont_bz.jpg";
        // 二维码图路径
        String qrcodePath = getXmlPath() + "image" + File.separator + "qrcode.jpg";
        // 错误图路径
        String errorPath = getXmlPath() + "image" + File.separator + "error.png";

        // logo图路径
        String logoPath = getXmlPath() + "image" + File.separator + "logo.png";

        final int width = 750;
        final int height = 1334;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        /**
         * 设置背景图
         */
        {
            Graphics graphics = image.getGraphics();
            BufferedImage bgImage = ImageIO.read(new File(imagePath));
            graphics.setColor(Color.RED);
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(bgImage, 0, 0, width, height, null);
            graphics.dispose();
        }

        {
            //二维码
            {
                int circleX = 443;
                int circleY = 482;
                int baseData = 125;

                Graphics graphics = image.createGraphics();
                BufferedImage posterImage;

                try {
                    posterImage = ImageIO.read(new URL(posterOutput.getPersonalQrCodeUrl()));
                } catch (Exception e) {
                    posterImage = ImageIO.read(new File(posterOutput.getPersonalQrCodeUrl()));
                }
                // 缩小图片消除锯齿的平滑处理
                graphics.drawImage(resize(posterImage,80,80),
                        circleX, circleY, null);
                graphics.dispose();
            }
        }
        /**
         * 头像
         */
        {
            int circleX = 318;
            int circleY = 895;
            int circleWidth = 112;
            int circleHeight = 112;
            {
                Graphics2D g2 = image.createGraphics();
                g2.setComposite(AlphaComposite.Src);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.WHITE);
                //图片是一个圆型
                Ellipse2D.Double shape = new Ellipse2D.Double(circleX, circleY, circleWidth, circleHeight);
                //需要保留的区域
                g2.setClip(shape);

                // 设置背景图
                BufferedImage bufferedImage = null;
                try {
                    String logo = posterOutput.getLogo();
                    if (logo.indexOf("http:") == -1 && logo.indexOf("https:") == -1 && logo.indexOf("image.myqcloud.com") != -1) {
                        logo = "http:" + logo;
                    }
                    bufferedImage = ImageIO.read(new URL(logo));
                    ByteArrayOutputStream successOutput = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "PNG", successOutput);

                    BufferedImage errorImage = ImageIO.read(new File(errorPath));
                    ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
                    ImageIO.write(errorImage, "PNG", errorOutput);

                    if (errorOutput.toString().equals(successOutput.toString())) {
                        bufferedImage = ImageIO.read(new File(logoPath));
                    } else {
                        if (logo.indexOf("image.myqcloud.com") != -1) {
                            logo += "?imageMogr2/auto-orient/crop/195x195";
                        }
                        bufferedImage = ImageIO.read(new URL(logo));
                    }
                } catch (Exception e) {
                    bufferedImage = ImageIO.read(new File(logoPath));
                }
                g2.drawImage(bufferedImage, circleX, circleY, circleWidth, circleHeight, null);
                g2.dispose();
            }

/*            {
                Graphics2D graphics = image.createGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //画笔是4.5个像素，BasicStroke的使用可以查看下面的参考文档
                //使画笔时基本会像外延伸一定像素，具体可以自己使用的时候测试
                Stroke s = new BasicStroke(4F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
                graphics.setStroke(s);
                graphics.setColor(new Color(249,234,160));
                graphics.drawOval(circleX, circleY, circleWidth, circleHeight);
                graphics.dispose();
            }*/
        }


        /**
         * 众筹者
         */
        {
            Font font_date = new Font("方正行楷_GBK", Font.PLAIN, 40);

            String nickName = posterOutput.getNickName();
            int textY = 1075;
            Graphics2D graphics2d = image.createGraphics();
            FontMetrics fontMetrics = graphics2d.getFontMetrics(font_date);
            // 计算出中心点 x 位置
            int centerX = image.getWidth() / 2;
            // 文字宽度
            int textWidth = fontMetrics.stringWidth(nickName);

            drawText(graphics2d, font_date, new Color(249,234,160), nickName, centerX - textWidth / 2, textY);

        }



        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //保存新图片
        ImageIO.write(image, formatName, bos);
        return bos.toByteArray();
    }


    /**
     * 实现图像的等比缩放
     *
     * @param source
     *            待处理的图片流
     * @param targetW
     *            宽度
     * @param targetH
     *            高度
     * @return
     */
    public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
        int width = source.getWidth();// 图片宽度
        int height = source.getHeight();// 图片高度
        return zoomInImage(source, targetW, targetH);
        // 图片宽高都太小时，强制放大图片
    }

    /**
     * 对图片进行强制放大或缩小
     *
     * @param originalImage
     *            原始图片
     * @return
     */
    public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) {
        BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());

        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return newImage;
    }

    /**
    * @Author yifeng
    * @Description integer转string
    * @Date 15:15 2019/3/28
    * @param object 被转的对象
    * @return
    **/
    public static String transfrom(Long object) {
        if (null != object && object > 0) {
            return object.toString();
        }
        return "";
    }
}